package com.though.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageConfig {

	private static final Logger logger = LoggerFactory.getLogger(MessageConfig.class);
	
	private static final String CONFIG = "/message-config.properties";

	private static final String CONFIG_TEMPLATE = "/message-config-template.properties";

	private volatile Params params;
	
	public MessageConfig() {
		init();
	}
	
	public void init() {
		InputStream in = MessageConfig.class.getResourceAsStream(CONFIG);
		if (in == null) {
			in = MessageConfig.class.getResourceAsStream(CONFIG_TEMPLATE);
			if (in == null) throw new RuntimeException("message-config.properties is not config");
		}
		this.params = loadConfigParams(in);
	}

	private Params loadConfigParams(InputStream in) {
		Properties properties = new Properties();
		try {
			properties.load(in);
			Params params = new Params();
			params.setAppKey(properties.getProperty("appKey"));
			params.setAppSecret(properties.getProperty("appSecret"));
			params.setHost(properties.getProperty("host"));
			params.setAppCode(properties.getProperty("appCode"));
			return params;
			
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error("Error:close oss properties file", e);
				}
			}
		}
	}

	public Params getConfigParams() {
		return params;
	}
}
